package rlink

import (
	"context"
	"fmt"
	"gitee.com/ruige_fun/util/rpwd"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// LinkMongoDB 连接 MongoDB 数据库，返回 *mongo.Database
func LinkMongoDB(dbName string, accPassword rpwd.AccountAndPassword) (*mongo.Database, error) {
	var DSN string
	host := accPassword.IP
	if host == "" {
		host = "127.0.0.1"
	}
	if accPassword.Password == "" {
		DSN = fmt.Sprint("mongodb://", host, ":", accPassword.Port)
	} else {
		DSN = fmt.Sprint("mongodb://", accPassword.Account, ":", accPassword.Password, "@", host, ":", accPassword.Port)
	}
	client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(DSN))
	if err != nil {
		fmt.Println("连接 MongoDB 数据库", dbName, "失败：", err)
		return nil, err
	}
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		fmt.Println("连接 MongoDB 数据库", dbName, "失败Ping：", err)
		return nil, err
	}
	database := client.Database(dbName)
	fmt.Println("连接 MongoDB 数据库", dbName, "成功！")
	return database, nil
}
